package com.lujianfei.filesend.ui.search.viewmodel

import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.lujianfei.common.LogUtils
import com.lujianfei.filesend.ui.search.adapter.SearchDeviceItem
import com.lujianfei.filesend.ui.search.model.MessageModel
import com.lujianfei.filesend.ui.search.model.MessageStatus
import com.lujianfei.filesend.ui.search.model.MessageType
import com.lujianfei.filetransfer.IPScanner
import com.lujianfei.filetransfer.ScanStatus
import com.lujianfei.filetransfer.TcpManager
import com.lujianfei.filetransfer.model.CustomModelBase
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


/**
 * Author: lujianfei
 * Date: 2023/10/16 17:52
 * Description: 搜索设备
 */

class SearchDeviceViewModel: ViewModel() {

    val title = ObservableField("搜索设备")

    val loading = ObservableBoolean(false)

    val messageList = ObservableArrayList<MessageModel>()
    fun onMessageReceive(ipaddress: String, message: String) {
        viewModelScope.launch {
            messageList.add(0,MessageModel(name = "", content = message, type = MessageType.Text, self = false, status = ObservableField(MessageStatus.Success)))
        }
    }

    fun showLoading() {
        viewModelScope.launch {
            loading.set(true)
        }
    }
    fun hideLoading() {
        viewModelScope.launch {
            loading.set(false)
        }
    }

    fun sendMessage(message: String) {
        val messageModel = MessageModel(name = "", content = message, self = true, status = ObservableField(MessageStatus.Sending), type = MessageType.Text)
        messageList.add(0, messageModel)
        TcpManager.instance.sendMessage(message = message, onSuccess = {
            viewModelScope.launch {
                messageModel.status.set(MessageStatus.Success)
            }
        }, onFailed = {
            viewModelScope.launch {
                messageModel.status.set(MessageStatus.Failed)
            }
        })
        scrollToEnd()
    }

    var onScrollToEnd:(()->Unit) ?= null
    private fun scrollToEnd() {
        onScrollToEnd?.invoke()
    }
}